package dev.tools.utils;

import java.io.*;
import java.lang.management.ManagementFactory;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AppUtils {

    private static String PID = "-1";

    private static Pattern packagePattern = Pattern.compile("package\\s*(\\S*);");

    private static Pattern classPattern = Pattern.compile("public\\s*class\\s*([a-zA-Z0-9_$]*)");

    static {
        // https://stackoverflow.com/a/7690178
        String jvmName = ManagementFactory.getRuntimeMXBean().getName();
        int index = jvmName.indexOf('@');

        if (index > 0) {
            try {
                PID = Long.toString(Long.parseLong(jvmName.substring(0, index)));
            } catch (Throwable e) {
                // ignore
            }
        }
    }

    public static String getPid() {
        return PID;
    }

    public static void copyStreamToFile(InputStream in, String outPath) throws Exception {
        try (OutputStream out = new FileOutputStream(outPath, false)) {
            copy(in, out, new byte[4096]);
        } catch (Throwable e) {
            throw e;
        }
    }

    public static long copy(InputStream input, OutputStream output, byte[] buffer) throws IOException {
        long count;
        int n;
        for (count = 0L; -1 != (n = input.read(buffer)); count += (long) n) {
            output.write(buffer, 0, n);
        }

        return count;
    }

    public static String getClassName(String newCode) {
        Matcher packageMatcher = packagePattern.matcher(newCode);
        Matcher classMatcher = classPattern.matcher(newCode);
        if (!(packageMatcher.find() && classMatcher.find())) {
            throw new IllegalStateException("This is an illegal class");
        }
        String className = packageMatcher.group(1) + "." + classMatcher.group(1);
        return className;
    }

}